//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'

//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'


//创建用户小仓库
const useUserStore = defineStore('User', {
  
  state: () => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      username: '',
      avatar: '',
      buttons: [],
    }
  },
  actions: {
    async userLogin(data) {
      //登录请求
      // const result = await reqLogin(data)
      const result = {code: 200, data: {token: 123}, message: "success"}
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data.token
        //本地存储持久化存储一份
        SET_TOKEN(result.data.token)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      // const result = await reqLogout()
      const result = {code: 200, message: "success"}
      if (result.code == 200) {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  }
})
export default useUserStore
